package com.ease.web.xwt.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.ClassUtils;

import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 
 * @author nathanleewei
 * 
 */
public class XComponentTemplateFactory {

	private static final transient Log log = LogFactory.getLog(XComponentTemplateFactory.class);

	private Map<String, Object> templateMap;

	private Configuration configuration;

	private XComponentTemplateFactory() {
		templateMap = new Hashtable<String, Object>();
		configuration = new Configuration();
		URL url = null;
		try {
			url = this.getClass().getClassLoader().getResource(ClassUtils.classPackageAsResourcePath(XComponentTemplateFactory.class) + '/' + "xwt.properties");
			InputStream in = url.openStream();

			if (null != in) {
				Properties p = new Properties();
				p.load(in);
				configuration.setSettings(p);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// if(null!=url) {
			// url.
			// }
			url = null;
		}
		configuration.setTemplateLoader(new ClassTemplateLoader(XComponentTemplateFactory.class, "/"));
	}

	static class XComponentTemplateFactoryHolder {
		static XComponentTemplateFactory instance = new XComponentTemplateFactory();
	}

	public static XComponentTemplateFactory getInstance() {
		return XComponentTemplateFactoryHolder.instance;
	}

	public Template getComponentTemplate(String templateFullName) {
		Object template = templateMap.get(templateFullName);
		if (template == null) {
			try {
				template = configuration.getTemplate(templateFullName);
			} catch (IOException e) {
				log.error("configuration getTemplate exception: templateFullyName=" + templateFullName, e);
			}

			if (template == null) {
				templateMap.put(templateFullName, new String("NULL"));
			} else {
				templateMap.put(templateFullName, template);
			}
			return (Template) template;

		} else if (template instanceof String) {
			return null;
		} else {
			return (Template) template;
		}

	}
}